//
// Created by Yang2 on 2022/4/28.
//

#include "MyGLRenderContext.h"
#include "../project/texture_map/TextureMapSample.h"

MyGLRenderContext *MyGLRenderContext::m_pContext = nullptr;

MyGLRenderContext *MyGLRenderContext::GetInstance() {
    if (m_pContext == nullptr) {
        m_pContext = new MyGLRenderContext();
    }
    return m_pContext;
}

void MyGLRenderContext::OnSurfaceChanged(int width, int height) {
    m_ScreenW = width;
    m_ScreenH = height;
}

void MyGLRenderContext::OnSurfaceCreated() {
    glClearColor(1.0f, .0f, .0f, 1.0f); //glClearColor只起到Set的作用，并不Clear任何  指定刷新颜色缓冲区时所用的颜色。所以，完成一个刷新过程是要 glClearColor(COLOR) 与 glClear(GL_COLOR_BUFFER_BIT) 配合使用
}

void MyGLRenderContext::OnDrawFrame() {


//    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);//表示要清除颜色缓冲以及深度缓冲和模板缓冲区
    if (m_pCurSample) {

        m_pCurSample->Init();
        m_pCurSample->Draw(m_ScreenW, m_ScreenH);
    }

}

void MyGLRenderContext::SetParamsInt(int paramType) {
    LOGCATE("MyGLRenderContext::SetParamsInt =%d ", paramType);
    switch (paramType) {
        case SAMPLE_TYPE_KEY_TRIANGLE:
            m_pCurSample = new TriangleSample();
            break;
        case SAMPLE_TYPE_KEY_TEXTURE_MAP:
            m_pCurSample = new TextureMapSample();
            break;
        default:
            m_pCurSample = nullptr;
            break;
    }
}

void MyGLRenderContext::SetImageData(int format, int width, int height, uint8_t *pData) {
    LOGCATE("MyGLRenderContext::SetImageData format=%d, width=%d, height=%d, pData=%p", format, width, height, pData);
    NativeImage nativeImage;
    nativeImage.format = format;
    nativeImage.width = width;
    nativeImage.height = height;
    nativeImage.ppPlane[0] = pData;

//    switch (format)
//    {
//        case IMAGE_FORMAT_NV12:
//        case IMAGE_FORMAT_NV21:
//            nativeImage.ppPlane[1] = nativeImage.ppPlane[0] + width * height;
//            break;
//        case IMAGE_FORMAT_I420:
//            nativeImage.ppPlane[1] = nativeImage.ppPlane[0] + width * height;
//            nativeImage.ppPlane[2] = nativeImage.ppPlane[1] + width * height / 4;
//            break;
//        default:
//            break;
//    }

    if (m_pCurSample) {
        m_pCurSample->LoadImage(&nativeImage);
    }
}

void MyGLRenderContext::DestroyInstance() {
    LOGCATE("MyGLRenderContext::DestroyInstance");
    if (m_pContext) {
        delete m_pContext;
        m_pContext = nullptr;
    }

}